package com.chatplus.application.service.wxmp.handler;

import com.chatplus.application.common.logging.SouthernQuietLogger;
import com.chatplus.application.common.logging.SouthernQuietLoggerFactory;
import com.chatplus.application.domain.entity.account.WechatUserEntity;
import com.chatplus.application.enumeration.WechatUserStatusEnum;
import com.chatplus.application.service.account.UserService;
import com.chatplus.application.service.account.WechatUserService;
import com.chatplus.application.service.wxmp.builder.TextBuilder;
import com.chatplus.application.service.wxmp.impl.WeChatMpService;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.message.WxMpXmlMessage;
import me.chanjar.weixin.mp.bean.message.WxMpXmlOutMessage;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 处理关注事件
 * 新用户走关注事件；
 * 老用户走扫码事件
 *
 * @author Binary Wang
 */
@Component
public class SubscribeHandler extends AbstractHandler {
    static final SouthernQuietLogger LOGGER = SouthernQuietLoggerFactory.getLogger(SubscribeHandler.class);

    public SubscribeHandler(WeChatMpService weChatMpService,
                            WechatUserService wechatUserService,
                            UserService userService) {
        super(weChatMpService, wechatUserService, userService);
    }

    @Override
    public WxMpXmlOutMessage handle(WxMpXmlMessage wxMessage,
                                    Map<String, Object> context,
                                    WxMpService wxMpService,
                                    WxSessionManager sessionManager) {
        String appId = wxMpService.getWxMpConfigStorage().getAppId();
        LOGGER.message("新关注用户").context("OPENID", wxMessage.getFromUser()).context("appId", appId).info();
        try {
            WechatUserEntity weChatUser = handleUser(appId, wxMessage.getFromUser(), WechatUserStatusEnum.FOLLOWED);
            // 这里是扫码登录的意思
            if (wxMessage.getEventKey().startsWith("qrscene_")) {
                return this.handleKey(weChatUser, wxMessage);
            }
            return new TextBuilder().build("感谢关注!,更多的功能正在开发中,敬请期待!",
                    wxMessage,
                    weChatMpService);
        } catch (Exception e) {
            LOGGER.message("关注事件处理失败").context("OPENID", wxMessage.getFromUser()).exception(e).error();
        }
        return null;
    }

    /**
     * 事理key事件
     */
    private WxMpXmlOutMessage handleKey(WechatUserEntity weChatUser, WxMpXmlMessage wxMpXmlMessage) {
        return this.handleByEventKey(wxMpXmlMessage.getEventKey(), weChatUser, wxMpXmlMessage);
    }
}
